<template>
  <div class="promotion-creation-container">
    <!-- Header -->
    <div class="header">
      <div class="header-left">
        <IconifyIconOffline icon="local-icon:logo" width="32" height="32" />
        <h1 class="header-title">快鸟先飞</h1>
      </div>
      <div class="header-right">
        <el-button @click="router.back()">返回</el-button>
      </div>
    </div>

    <div class="main-content">
      <!-- 左侧导航树 -->
      <div class="left-side" :class="{ 'is-collapsed': isCollapsed }">
        <div class="collapse-btn" @click="toggleCollapse">
          <el-icon>
            <ArrowRight v-if="isCollapsed" />
            <ArrowLeft v-else />
          </el-icon>
        </div>
        <el-tree
          :data="treeData"
          :props="defaultProps"
          default-expand-all
          node-key="id"
          highlight-current
          :current-node-key="currentNodeKey"
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <span class="tree-node" :title="node.label">
              <el-icon v-if="data.type === 'campaign'"><Briefcase /></el-icon>
              <el-icon v-else-if="data.type === 'unit'"><Grid /></el-icon>
              <el-icon v-else-if="data.type === 'creative'"
                ><Picture
              /></el-icon>
              <span class="node-label">{{ node.label }}</span>
            </span>
          </template>
        </el-tree>
      </div>

      <!-- 创建表单容器 -->
      <div class="creation-form-container">
        <h2 class="form-title">创建{{ getFormTitle }}</h2>

        <!-- 使用封装的广告计划组件 -->
        <campaign-form
          v-if="type === 'campaign'"
          ref="createFormRef"
          v-model="createForm"
          :is-read-only="route.query.campaignId"
        />

        <!-- 创建广告组表单 -->
        <div v-if="type === 'unit'">
          <!-- 显示广告计划信息（只读模式） -->
          <el-collapse v-model="activeNames">
            <el-collapse-item title="广告计划信息" name="广告计划信息">
              <template #title>
                <div class="campaign-info-title">广告计划信息</div>
              </template>
              <campaign-form
                v-model="selectedCampaignData"
                :is-read-only="true"
                :preset-data="selectedCampaign"
                default-collapse
              />
            </el-collapse-item>

            <el-collapse-item title="广告组信息" name="广告组信息">
              <template #title>
                <h3 class="campaign-info-title">广告组信息</h3>
              </template>
              <unit-form
                ref="unitFormRef"
                v-model="unitForm"
                :is-read-only="route.query.unitId"
                :selected-campaign="selectedCampaign"
              />
            </el-collapse-item>
          </el-collapse>
        </div>

        <!-- 创建广告创意表单 -->
        <el-form
          v-if="type === 'creative'"
          ref="creativeFormRef"
          :model="creativeForm"
          :rules="creativeRules"
          label-width="120px"
          class="creation-form"
        >
          <!-- 基本信息分组 -->
          <div class="form-group">
            <div class="form-group-title">基本信息</div>
            <div class="form-group-content">
              <!-- 显示所属广告计划 -->
              <el-form-item label="所属广告计划">
                <el-input :model-value="selectedCampaignName" disabled />
              </el-form-item>

              <!-- 显示所属广告组 -->
              <el-form-item label="所属广告组">
                <el-input :model-value="selectedUnitName" disabled />
              </el-form-item>

              <!-- 创意名称 -->
              <el-form-item label="创意名称" prop="creativeName">
                <el-input
                  v-model="creativeForm.creativeName"
                  placeholder="请输入创意名称"
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>
            </div>
          </div>

          <!-- 创意内容分组 -->
          <div class="form-group">
            <div class="form-group-title">创意内容</div>
            <div class="form-group-content">
              <!-- 创意类型 -->
              <el-form-item label="创意类型" prop="creativeType">
                <el-select
                  v-model="creativeForm.creativeType"
                  placeholder="请选择创意类型"
                >
                  <!-- <el-option label="图片创意" :value="2" /> -->
                  <el-option label="视频创意" :value="1" />
                </el-select>
              </el-form-item>

              <el-form-item
                label="是否使用应用图标和名称	"
                prop="useUnitAppIconAndName"
              >
                <el-switch v-model="creativeForm.useUnitAppIconAndName" />
              </el-form-item>

              <el-form-item label="头像" prop="avatarId">
                <el-select
                  v-model="creativeForm.avatarId"
                  placeholder="请选择头像"
                  class="avatar-select"
                >
                  <template #prefix>
                    <img
                      v-if="selectedAvatar"
                      :src="selectedAvatar.avatarUrl"
                      class="selected-avatar"
                    />
                  </template>
                  <el-option
                    v-for="item in avatarList"
                    :key="item.avatarId"
                    :value="item.avatarId"
                    class="avatar-option"
                  >
                    <div class="avatar-option-content">
                      <img :src="item.avatarUrl" class="avatar-image" />
                      <span class="avatar-description">{{
                        item.description
                      }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>

              <!-- 视频素材选择 -->
              <el-form-item
                v-if="creativeForm.creativeType === 1"
                label="选择视频"
                prop="photoId"
              >
                <div class="video-selector">
                  <el-button
                    :disabled="!selectedCampaign?.adAccountId"
                    :title="
                      !selectedCampaign?.adAccountId ? '请先选择广告账户' : ''
                    "
                    @click="openVideoLibrary"
                  >
                    <el-icon
                      class="refresh-icon"
                      @click.stop="refreshVideoList"
                    >
                      <Refresh />
                    </el-icon>
                    选择视频
                  </el-button>
                  <span
                    v-if="selectedVideo || creativeForm.material"
                    class="selected-video-name"
                  >
                    已选择:
                    {{ (selectedVideo || creativeForm.material)?.materialName }}
                  </span>
                </div>
              </el-form-item>

              <!-- 广告语 -->
              <el-form-item label="广告语" prop="subTitle">
                <el-input
                  v-model="creativeForm.subTitle"
                  placeholder="请输入与公司主体、投放产品相关的广告口号"
                  maxlength="20"
                  show-word-limit
                />
              </el-form-item>

              <!-- 广告描述 -->
              <el-form-item label="描述" prop="desc">
                <el-input
                  v-model="creativeForm.desc"
                  type="textarea"
                  placeholder="请输入与公司主体、投放产品相关的广告描述"
                  maxlength="45"
                  show-word-limit
                />
              </el-form-item>

              <!-- 行动号召按钮 -->
              <el-form-item label="行动号召按钮" prop="callToAction">
                <el-select
                  v-model="creativeForm.callToAction"
                  placeholder="请选择行动号召按钮"
                >
                  <el-option label="玩游戏" value="1" />
                  <el-option label="立即安装" value="2" />
                  <el-option label="一键下载" value="3" />
                  <el-option label="更多精彩" value="4" />
                  <el-option label="了解详情" value="5" />
                  <el-option label="立即下载" value="6" />
                  <el-option label="折扣促销" value="7" />
                  <el-option label="打折中" value="8" />
                  <el-option label="去逛逛" value="9" />
                  <el-option label="立即购买" value="10" />
                </el-select>
              </el-form-item>

              <!-- Deeplink -->
              <el-form-item label="Deeplink" prop="deepLink">
                <el-input
                  v-model="creativeForm.deepLink"
                  placeholder="请输入Deeplink"
                />
              </el-form-item>
            </div>
          </div>
        </el-form>

        <div class="form-footer">
          <el-button v-if="!isHistory" @click="router.back()">取消</el-button>
          <el-button v-if="!isHistory" @click="handleCreateCurrent"
            >仅创建{{ getFormTitle }}</el-button
          >
          <el-button type="primary" @click="handleNext">下一步</el-button>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="videoDialogVisible"
      title="选择视频"
      width="90%"
      destroy-on-close
    >
      <!-- 添加搜索框 -->
      <div class="search-container mb-4">
        <el-input
          v-model="searchQuery"
          placeholder="请输入视频名称搜索"
          class="search-input"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <div class="video-list">
        <el-row :gutter="16">
          <el-col
            v-for="item in videoList"
            :key="item.id"
            :span="6"
            class="mb-4"
          >
            <el-card
              :body-style="{ padding: '0px' }"
              class="video-card"
              :class="{ 'is-selected': selectedVideo?.id === item.id }"
              @click="handleVideoSelect(item)"
            >
              <video
                :src="item.ossPath"
                class="video-preview"
                preload="metadata"
              />
              <div class="video-info p-2">
                <div class="video-name text-ellipsis">
                  {{ item.materialName }}
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="videoPagination.currentPage"
          v-model:page-size="videoPagination.pageSize"
          :total="videoPagination.total"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleVideoSizeChange"
          @current-change="handleVideoCurrentChange"
        />
      </div>

      <template #footer>
        <el-button @click="videoDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleVideoConfirm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  onMounted,
  onBeforeUnmount,
  nextTick,
  watch,
  computed
} from "vue";
import { useAppStoreHook } from "@/store/modules/app";
import { useSettingStoreHook } from "@/store/modules/settings";
import { useRouter, useRoute } from "vue-router";
import {
  getAdAccounts,
  createCampaign,
  createUnit,
  createCreative,
  getMaterialVideoList
} from "@/api/promotion";
import { getAvatarList } from "@/api/common.ts";
import { getVideoList, MaterialState } from "@/api/material";
import { ElMessage } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import {
  Plus,
  Briefcase,
  Grid,
  Picture,
  Search,
  ArrowLeft,
  ArrowRight
} from "@element-plus/icons-vue";
// import Refresh from "@iconify-icons/ep/refresh";
// import Upload from "@iconify-icons/ep/upload";
// import EditPen from "@iconify-icons/ep/edit-pen";
import { useUnitSelect, useCampaignSelect } from "./utils/hooks";
import { getSessionStorage, removeSessionStorage } from "@/utils/storage";
import CampaignForm from "./components/CampaignForm.vue";
import UnitForm from "./components/UnitForm.vue";
import { debounce } from "lodash-es";
import { setSessionStorage } from "@/utils/storage";

defineOptions({
  name: "PromotionCreation"
});

const router = useRouter();
const route = useRoute();

const activeNames = ref(["广告组信息"]);
// 获取路由参数
const type = ref("campaign");
const campaignId = ref("");
const unitId = ref("");

// 从 sessionStorage 获取选中的广告计划和广告组数据
const selectedCampaign = ref<any>(getSessionStorage("selectedCampaign"));
const selectedUnit = ref<any>(getSessionStorage("selectedUnit"));

// 表单引用
const createFormRef = ref();
const unitFormRef = ref();
const creativeFormRef = ref();

// Mock数据 - 广告计划和广告组
const mockCampaigns = [
  { id: "1", name: "广告计划1" },
  { id: "2", name: "广告计划2" },
  { id: "3", name: "广告计划3" }
];

const mockUnits = [
  { id: "1", name: "广告组1", campaignId: "1" },
  { id: "2", name: "广告组2", campaignId: "1" },
  { id: "3", name: "广告组3", campaignId: "2" },
  { id: "4", name: "广告组4", campaignId: "3" }
];

// 用于在广告组创建表单中显示选中的广告计划信息
const selectedCampaignData = ref({});

// 树形结构相关数据
const treeData = ref([]);
const defaultProps = {
  children: "children",
  label: "label"
};
const expandedKeys = ref<string[]>([]);
const currentNodeKey = ref("");

// 计算属性 - 所选广告计划和广告组名称
const selectedCampaignName = computed(() => {
  return selectedCampaign.value?.campaignName || "未知广告计划";
});

const selectedUnitName = computed(() => {
  return selectedUnit.value?.unitName || "未知广告组";
});

// 计算属性 - 表单标题
const getFormTitle = computed(() => {
  switch (type.value) {
    case "campaign":
      return "广告计划";
    case "unit":
      return "广告组";
    case "creative":
      return "广告创意";
    default:
      return "";
  }
});

// 创建广告计划表单数据
const createForm = ref({
  adAccountId: "", // 投放账户
  adCategory: 1, // 广告分类，默认1:效果广告
  campaignType: 3, // 营销目标，默认3:转化
  marketingType: null, // 推广对象
  deliveryStrategy: null, // 出价策略
  cboAuthorized: false, // 计划预算优化
  budgetType: null, // 每日预算类型
  dayBudget: 0, // 每日固定预算
  budgetSchedule: [0, 0, 0, 0, 0, 0, 0], // 固定日期预算，对应周一到周日
  campaignName: "" // 计划名称
});

// 创建广告组表单数据
const unitForm = ref({
  unitName: "",
  budgetType: "",
  dayBudget: 0,
  gender: "",
  ageList: [],
  countryRegionInfoList: [],
  languageList: [],
  deviceBrandCodeList: [],
  devicePriceInfoList: [],
  osTypeAndVersionList: [],
  contentInterestCodeList: [],
  placements: [],
  linkType: "",
  ocpxActionType: "",
  ocpxActionTypeLimit: ""
});

// 创建广告创意表单数据
const creativeForm = ref({
  creativeName: "",
  creativeType: 1,
  photoId: null,
  subTitle: "",
  desc: "",
  callToAction: "",
  deepLink: "",
  material: null,
  useUnitAppIconAndName: false,
  avatarId: null
});

// 视频选择相关
const selectedVideo = ref(null);
const videoRefreshCooldown = ref(false);
const videoRefreshCount = ref(0);

// 搜索相关
const searchQuery = ref("");

// 处理搜索输入
const handleSearch = debounce(() => {
  videoPagination.value.currentPage = 1; // 重置页码
  fetchVideoList();
}, 300);
const lastRefreshTime = ref(null);

// 创建广告创意表单验证规则
const creativeRules = {
  creativeName: [
    { required: true, message: "请输入广告创意名称", trigger: "blur" },
    { max: 100, message: "超出可输入最长创意名称", trigger: "blur" }
  ],
  creativeType: [
    { required: true, message: "请选择创意类型", trigger: "change" }
  ],
  photoId: [{ required: true, message: "请选择视频素材", trigger: "change" }],
  subTitle: [{ max: 20, message: "超出可输入最长计划名称", trigger: "blur" }],
  desc: [
    { required: true, message: "请输入广告描述", trigger: "blur" },
    { max: 45, message: "超出可输入最长计划名称", trigger: "blur" }
  ],
  callToAction: [
    { required: true, message: "请选择行动号召按钮", trigger: "change" }
  ],
  avatarId: [
    {
      required: true,
      message: "请选择头像",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (!creativeForm.value.useUnitAppIconAndName && !value) {
          callback(new Error("请选择头像"));
        } else {
          callback();
        }
      }
    }
  ]
};
const videoDialogVisible = ref(false);
const videoList = ref([]);
const avatarList = ref([]);
const loading = ref(false);
const videoPagination = ref({
  currentPage: 1,
  pageSize: 12,
  total: 0
});

const fetchAvatarList = async () => {
  console.debug(selectedCampaign.value, "---selectedCampaign---");
  if (selectedCampaign.value?.adAccountId) {
    const data = await getAvatarList({
      adAccountId: selectedCampaign.value.adAccountId,
      size: -1
    });
    avatarList.value = data.list;
  }
};

// 打开视频库弹窗
const openVideoLibrary = async () => {
  videoDialogVisible.value = true;
  await fetchVideoList();
};

// 获取视频列表
const fetchVideoList = async () => {
  try {
    loading.value = true;
    const params = {
      state: MaterialState.AuditSuccess,
      page: videoPagination.value.currentPage,
      size: videoPagination.value.pageSize,
      name: searchQuery.value // 添加搜索参数
    };
    const res = await getVideoList(params);
    if (res) {
      videoList.value = res.list;
      videoPagination.value.total = res.total;
    }
  } catch (error) {
    console.error("获取视频列表失败:", error);
    ElMessage.error("获取视频列表失败");
  } finally {
    loading.value = false;
  }
};

// 选择视频
const handleVideoSelect = video => {
  selectedVideo.value = video;
};

// 确认选择视频
const handleVideoConfirm = () => {
  if (!selectedVideo.value) {
    ElMessage.warning("请选择视频");
    return;
  }
  creativeForm.value.photoId = selectedVideo.value.ksVideoId;
  creativeForm.value.material = selectedVideo.value;
  videoDialogVisible.value = false;
};

// 分页相关方法
const handleVideoSizeChange = val => {
  videoPagination.value.pageSize = val;
  fetchVideoList();
};

const handleVideoCurrentChange = val => {
  videoPagination.value.currentPage = val;
  fetchVideoList();
};

// 刷新视频列表
const refreshVideoList = () => {
  if (videoRefreshCooldown.value) {
    return;
  }

  const now = Date.now();
  const today = new Date().setHours(0, 0, 0, 0);

  // 重置每日刷新次数
  if (lastRefreshTime.value < today) {
    videoRefreshCount.value = 0;
  }

  // 检查每日刷新次数限制
  if (videoRefreshCount.value >= 5) {
    ElMessage.warning("当日刷新次数已达上限");
    return;
  }

  // 设置冷却时间
  videoRefreshCooldown.value = true;
  setTimeout(() => {
    videoRefreshCooldown.value = false;
  }, 60000);

  // 更新计数器和时间戳
  videoRefreshCount.value++;
  lastRefreshTime.value = now;

  // TODO: 调用API刷新视频列表
};

const { unitOptions, loadUnitOptions } = useUnitSelect();

// 根据当前类型和选中的广告计划/广告组生成树形结构
const generateTreeData = () => {
  const tree = [];
  // 如果有选中的广告计划
  if (selectedCampaign.value) {
    const campaignNode = {
      id: "campaign-" + selectedCampaign.value.campaignId,
      label: selectedCampaignName.value,
      type: "campaign",
      children: []
    };

    // 如果有选中的广告组，添加为广告计划的子节点
    if (selectedUnit.value) {
      const unitNode = {
        id: "unit-" + selectedUnit.value.unitId,
        label: selectedUnitName.value,
        type: "unit",
        children: []
      };

      // 如果当前是创建创意，添加一个创意节点
      if (type.value === "creative") {
        unitNode.children.push({
          id: "creative-new",
          label: "新建创意",
          type: "creative"
        });
      }

      campaignNode.children.push(unitNode);
    }
    // 如果当前是创建广告组，添加一个广告组节点
    else if (type.value === "unit") {
      campaignNode.children.push({
        id: "unit-new",
        label: "新建广告组",
        type: "unit"
      });
    }

    tree.push(campaignNode);
  }
  // 如果当前是创建广告计划，添加一个广告计划节点
  else if (type.value === "campaign") {
    tree.push({
      id: "campaign-new",
      label: "新建广告计划",
      type: "campaign"
    });
  }

  return tree;
};

// 处理树节点点击
const handleNodeClick = data => {
  console.log("树节点点击:", data);
  if (data.type == "campaign" && data.id && data.id != "campaign-new") {
    router.replace({
      path: "/promotion/creation",
      query: {
        type: "campaign",
        campaignId: selectedCampaign.value.campaignId
      }
    });
  }
  if (data.type == "unit" && data.id && data.id != "unit-new") {
    router.replace({
      path: "/promotion/creation",
      query: {
        type: "unit",
        unitId: selectedUnit.value.unitId
      }
    });
  }
  // 这里可以添加节点点击后的处理逻辑，比如导航到相应页面
};

const formatFormData = (formData: any) => {
  const newFormData = { ...formData };
  if (type.value === "campaign") {
    // 提取accountId
    const accountId = newFormData.accountId;
    delete newFormData.accountId;

    // 使用组件暴露的格式化方法获取格式化后的数据
    return {
      adAccountId: accountId,
      data: createFormRef.value.formatFormData()
    };
  }

  return newFormData;
};

// 处理仅创建当前步骤
const handleCreateCurrent = async (isNext: boolean) => {
  try {
    let result, formRef, formData;
    switch (type.value) {
      case "campaign": {
        const params = { ...createForm.value };
        if (params.budgetType === 2) {
          params.dayBudget = params.dayBudget * Math.pow(10, 6);
          delete params.budgetSchedule;
        } else if (params.budgetType === 3) {
          delete params.dayBudget;
        } else {
          delete params.dayBudget;
          delete params.budgetSchedule;
        }
        delete params.accountId;
        params.cboAuthorized = params.cboAuthorized ? 1 : 0;
        const apiParams = {
          data: params,
          adAccountId: params.adAccountId
        };
        delete apiParams.data.adAccountId;
        result = await createCampaign(apiParams as any);
        ElMessage.success("广告计划创建成功");

        //更新存储数据
        selectedCampaign.value = {
          ...apiParams,
          ...apiParams.data,
          campaignId: result.data?.[0].campaignId
        };
        setSessionStorage("selectedCampaign", selectedCampaign.value);
        break;
      }
      case "unit":
        formRef = unitFormRef.value;
        console.log(selectedCampaign, "---selectedCampaign---");
        console.log(formRef, "---formRef---");
        try {
          if (
            !selectedCampaign.value ||
            !selectedCampaign.value.adAccountId ||
            !selectedCampaign.value.campaignId
          ) {
            ElMessage.error("缺少广告账户或广告计划信息，请检查");
            return;
          }

          // 验证表单数据
          const validatedData = await formRef.validate();

          // 确保adAccountId和campaignId为数字类型
          const adAccountId = Number(selectedCampaign.value.adAccountId);
          const campaignId = Number(selectedCampaign.value.campaignId);

          if (isNaN(adAccountId) || isNaN(campaignId)) {
            ElMessage.error("广告账户ID或广告计划ID格式不正确");
            return;
          }

          // 构建API参数
          const apiData = {
            adAccountId: adAccountId,
            campaignId: campaignId,
            data: validatedData
          };

          // 打印完整请求参数，方便调试
          console.log("创建广告组请求参数:", JSON.stringify(apiData, null, 2));

          // 调用创建广告组API
          result = await createUnit(apiData);

          console.log("创建广告组成功:", result);
          ElMessage.success(`创建${getFormTitle.value}成功`);

          //更新存储数据
          selectedUnit.value = {
            ...apiData,
            ...apiData.data,
            ...result.data?.[0]
          };
          setSessionStorage("selectedUnit", selectedUnit.value);
          !isNext && router.back();
        } catch (error) {
          console.error(`创建${getFormTitle.value}失败:`, error);

          // 提取错误信息
          let errorMsg = "";
          if (error.response && error.response.data) {
            errorMsg =
              error.response.data.msg || JSON.stringify(error.response.data);
          } else if (error.msg) {
            // 如果是API返回的错误
            errorMsg = error.msg;
            // 尝试提取字段验证错误并格式化
            if (errorMsg.includes("validation")) {
              const matches = errorMsg.match(
                /Key: '([^']+)' Error:Field validation for '([^']+)' failed on the '([^']+)' tag/g
              );
              if (matches && matches.length > 0) {
                errorMsg =
                  "表单数据不完整: " +
                  matches
                    .map(m => {
                      const field = m.match(
                        /Field validation for '([^']+)'/
                      )[1];
                      const rule = m.match(/failed on the '([^']+)'/)[1];
                      return `${field}(${rule})`;
                    })
                    .join(", ");
              }
            }
          } else if (error.message) {
            errorMsg = error.message;
          } else {
            errorMsg = "未知错误";
          }

          ElMessage.error(`创建${getFormTitle.value}失败: ${errorMsg}`);
        }
        break;
      case "creative":
        formRef = creativeFormRef.value;
        formData = { ...creativeForm.value };
        await formRef.validate(async (valid, fields) => {
          if (valid) {
            try {
              // 检查必要的关联数据是否存在
              if (!selectedCampaign.value || !selectedUnit.value) {
                ElMessage.error("缺少广告计划或广告组信息，请检查");
                return;
              }

              // 构建API参数
              const apiData = {
                adAccountId: Number(selectedCampaign.value.adAccountId),
                data: {
                  campaignId: Number(selectedCampaign.value.campaignId),
                  unitId: Number(selectedUnit.value.unitId),
                  creativeName: creativeForm.value.creativeName,
                  creativeType: creativeForm.value.creativeType,
                  photoId: creativeForm.value.photoId,
                  adCategory: 1,
                  subTitle: creativeForm.value.subTitle,
                  desc: creativeForm.value.desc,
                  callToAction: creativeForm.value.callToAction
                    ? Number(creativeForm.value.callToAction)
                    : null,
                  deepLink: creativeForm.value.deepLink,
                  materialType: creativeForm.value.creativeType,
                  useUnitAppIconAndName:
                    creativeForm.value.useUnitAppIconAndName,
                  avatarId: creativeForm.value.avatarId
                }
              };

              // 打印完整请求参数，方便调试
              console.log(
                "创建广告创意请求参数:",
                JSON.stringify(apiData, null, 2)
              );

              const res = await createCreative(apiData);
              ElMessage.success(`创建${getFormTitle.value}成功`);
              router.back();
            } catch (error) {
              console.error(`创建${getFormTitle.value}失败:`, error);
              ElMessage.error(
                `创建${getFormTitle.value}失败: ${error.message || "未知错误"}`
              );
            }
          } else {
            console.error("表单验证失败:", fields);
          }
        });
        break;
    }
    !isNext && router.back();
    return result;
  } catch (error) {
    console.error("创建失败:", error);
    ElMessage.error("创建失败");
  }
};

const isHistoryNext = () => {
  // 根据当前类型决定下一步操作
  if (type.value === "campaign") {
    let query: any = {
      type: "unit"
    };
    console.log(selectedUnit.value, "---selectedUnit.value---");
    if (selectedUnit.value?.unitId) {
      query["unitId"] = selectedUnit.value.unitId;
    }
    router.replace({
      path: "/promotion/creation",
      query
    });
  } else if (type.value === "unit") {
    // 导航到创建广告创意页面
    router.replace(`/promotion/creation?type=creative`);
  } else {
  }
};
// 处理下一步操作
const handleNext = async () => {
  try {
    if (isHistory.value) {
      isHistoryNext();
      return;
    }
    // 调用 handleCreateCurrent 创建当前内容
    const result = await handleCreateCurrent(true);
    console.log(result, "--result--");
    if (!result) return;

    // 根据当前类型决定下一步操作
    if (type.value === "campaign") {
      // 保存创建的广告计划信息
      // 更新树形结构
      treeData.value = generateTreeData();
      // 导航到创建广告组页面
      // 跳转到创建页面
      router.replace({
        path: "/promotion/creation",
        query: {
          type: "unit",
          campaignId: result.data?.[0].campaignId
        }
      });
      // window.location.reload();
    } else if (type.value === "unit") {
      // 保存创建的广告组信息
      // selectedUnit.value = result;
      // 更新树形结构
      // treeData.value = generateTreeData();
      // 导航到创建广告创意页面
      router.replace({
        path: "/promotion/creation",
        query: {
          type: "creative",
          campaignId: selectedUnit.value.campaignId,
          unitId: selectedUnit.value.unitId
        }
      });
    } else if (type.value === "creative") {
      // 创建完广告创意后，返回到创建广告组页面
      router.replace(`/promotion/index`);
    }
  } catch (error) {
    console.error("创建失败:", error);
    ElMessage.error("创建失败");
  }
};
const initializeForm = async () => {
  // 获取路由参数
  type.value = (route.query.type as string) || "campaign";
  console.log(
    selectedCampaign.value,
    "--selectedCampaign--",
    selectedUnit.value,
    "--selectedUnit--"
  );
  if (selectedCampaign.value) {
    // 否则使用 sessionStorage 中的数据
    campaignId.value = selectedCampaign.value.campaignId;
    createForm.value = { ...selectedCampaign.value };
    // selectedCampaignData.value = { ...selectedCampaign.value };
    // console.log(selectedCampaignData.value, "--selectedCampaignData--");
  }

  // 如果是创建广告组，处理广告计划数据
  // if (type.value === "unit" && selectedCampaign.value) {
  //   // 确保数据中包含广告账户名称
  //   if (
  //     !selectedCampaign.value.accountName &&
  //     selectedCampaign.value.adAccountId
  //   ) {
  //     // 获取广告账户列表，找到匹配的账户名称
  //     const accounts = await getAdAccounts();
  //     if (accounts && accounts.length > 0) {
  //       const matchedAccount = accounts.find(
  //         account => account.adAccountId === selectedCampaign.value.adAccountId
  //       );
  //       if (matchedAccount) {
  //         selectedCampaign.value.accountName = matchedAccount.adAccountName;
  //       } else {
  //         selectedCampaign.value.accountName = `账户ID: ${selectedCampaign.value.adAccountId}`;
  //       }
  //     }
  //   }
  //   selectedCampaignData.value = { ...selectedCampaign.value };
  // }

  // 如果有选中的广告组数据;
  if (selectedUnit.value) {
    unitId.value = selectedUnit.value.unitId;
    unitForm.value = { ...selectedUnit.value };
  }

  loadUnitOptions();
  // 生成树形结构数据
  treeData.value = generateTreeData();

  // 设置默认展开的节点
  // if (selectedCampaign.value) {
  //   expandedKeys.value = ["campaign-" + selectedCampaign.value.campaignId];
  // }
  // 设置当前选中节点
  if (type.value == "campaign") {
    currentNodeKey.value = "campaign-new";
  } else if (type.value == "unit") {
    currentNodeKey.value = "unit-new";
  } else {
    currentNodeKey.value = "creative-new";
  }
  if (!avatarList.value.length) {
    fetchAvatarList();
  }
};
watch(
  () => route.query,
  () => {
    initializeForm();
  },
  { deep: true }
);

const isHistory = computed(() => {
  return (
    (route.query?.campaignId && route.query.type == "campaign") ||
    (route.query?.unitId && route.query.type == "unit")
  );
});
onMounted(() => {
  console.log(selectedCampaign.value, selectedUnit.value, "ssssss");
  getMaterialVideoList({
    size: 10,
    page: 1,
    adAccountId: 71894279
  });

  initializeForm();
});

// 组件卸载前清理 sessionStorage 中的数据
onBeforeUnmount(() => {
  // removeSessionStorage("selectedCampaign");
  // removeSessionStorage("selectedUnit");
});

// 在 script setup 部分添加计算属性
const selectedAvatar = computed(() => {
  return avatarList.value.find(
    item => item.avatarId === creativeForm.value.avatarId
  );
});

const isCollapsed = ref(true);
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};
</script>

<style lang="scss" scoped>
.promotion-creation-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
  width: 100%; /* 占据父容器80% */
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  width: 100%;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-title {
  margin-left: 12px;
  font-size: 18px;
  font-weight: bold;
}

.main-content {
  display: flex;
  flex: 1;
}

.left-side {
  width: 240px;
  border-top: 1px solid var(--el-border-color-light);
  padding: 16px;
  overflow-x: hidden;
  overflow-y: auto;
  background-color: #fff;
  position: relative;
  transition: all 0.3s ease;

  &.is-collapsed {
    width: 14px;
    padding: 16px 0;
    background-color: #fff !important;

    .el-tree {
      opacity: 0;
      pointer-events: none;
    }
  }
}

.collapse-btn {
  position: absolute;
  right: 0px;
  top: 300px;
  transform: translateY(-50%);
  width: 14px;
  height: 24px;
  background-color: #fff;
  border: 1px solid var(--el-border-color-light);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1;
  transition: all 0.3s ease;
  &:hover {
    background-color: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
  }
}

.creation-form-container {
  flex: 1;
  margin: 20px;
  padding: 24px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.form-title {
  margin-bottom: 24px;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}

.creation-form {
  margin-top: 20px;
}

/* 表单分组样式 */
.form-group {
  margin-bottom: 28px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  overflow: hidden;
}

.form-group-title {
  padding: 12px 16px;
  font-weight: 600;
  font-size: 16px;
  background-color: #f6f9fe;
  border-bottom: 1px solid #e5e7eb;
}

.form-group-content {
  padding: 16px;
}

.form-footer {
  margin-top: 24px;
  text-align: center;
}

.campaign-info-title {
  font-size: 16px;
  display: flex;
  font-weight: 600;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
  min-width: 0;
  font-size: 14px;
}

.node-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.el-tree-node__content) {
  padding: 8px;
  border-radius: 4px;
}

:deep(.el-tree-node__content:hover) {
  background-color: var(--el-fill-color-light);
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
.video-selector {
  display: flex;
  align-items: center;
  gap: 12px;

  .refresh-icon {
    margin-right: 4px;
    font-size: 14px;
    cursor: pointer;

    &.disabled {
      color: #c0c4cc;
      cursor: not-allowed;
    }
  }

  .selected-video-name {
    color: #606266;
    font-size: 14px;
  }
}
.video-list {
  min-height: 400px;
}

.video-card {
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  &.is-selected {
    border: 2px solid var(--el-color-primary);
  }
}

.video-preview {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.video-info {
  padding: 8px;
}

.video-name {
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}
.search-container {
  padding: 0 16px;

  .search-input {
    width: 300px;
  }
}

.avatar-select {
  width: 100%;

  :deep(.el-input__wrapper) {
    padding: 0 8px;
  }

  :deep(.el-input__inner) {
    height: 40px;
    padding-left: 42px; // 为头像预留空间
  }

  :deep(.el-input__prefix) {
    display: flex;
    align-items: center;
    margin-right: 8px;
  }

  :deep(.selected-avatar) {
    width: 34px;
    height: 34px;
    border-radius: 50%;
    object-fit: cover;
    border: 1px solid #e0e0e0;
  }

  :deep(.el-input__suffix) {
    display: none;
  }
}

.avatar-option {
  height: 40px;

  .avatar-option-content {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .avatar-image {
    width: 34px;
    height: 34px;
    border-radius: 50%;
    object-fit: cover;
    border: 1px solid #e0e0e0;
  }

  .avatar-description {
    font-size: 14px;
    color: #333;
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

:deep(.el-select-dropdown__item) {
  &.selected {
    .avatar-option-content {
      .avatar-description {
        color: var(--el-color-primary);
      }
      .avatar-image {
        border-color: var(--el-color-primary);
      }
    }
  }
}

:deep(.el-select-dropdown__wrap) {
  max-height: 300px;
}

:deep(.el-select-dropdown__list) {
  padding: 4px 0;
}
</style>
